package cn.com.open.ms.ecgpaasdatarest.log;


import cn.com.open.ms.ecgpaasdatarest.common.Constant;
import cn.com.open.ms.ecgpaasdatarest.utils.DateUtil;
import cn.com.open.ms.ecgpaasdatarest.utils.IpUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class LogFilter implements Filter {

    @Autowired
    private ServiceLogSender serviceLogSender;
    @Value("${api.log.onOff}")
    private String apiLogOnOff;

    @Override
    public void init(FilterConfig config) {
        //do nothing
    }

	@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (Constant.ON.equals(apiLogOnOff)) {
            HttpServletRequest req = (HttpServletRequest) request;
            if (response.getCharacterEncoding() == null) {
                response.setCharacterEncoding("UTF-8");
            }
            HttpServletResponse resp = (HttpServletResponse) response;

            JSONObject apiServiceLog = new JSONObject();
            apiServiceLog.put(LogConstant.REQUEST_PARAMS, requestParamsToJSON(req));
            apiServiceLog.put(LogConstant.IP, IpUtil.getIpAddr(req));
            apiServiceLog.put(LogConstant.REQUEST_URL, req.getRequestURL().toString());
            apiServiceLog.put(LogConstant.APP_KEY, req.getHeader("appKey"));
            apiServiceLog.put(LogConstant.CREATE_TIME, DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            apiServiceLog.put(LogConstant.HTTP_METHOD, req.getMethod());
            apiServiceLog.put(LogConstant.REQUEST_PATH, req.getRequestURI());
            apiServiceLog.put(LogConstant.HTTP_RESPONSE_STATUS, String.valueOf(resp.getStatus()));
            apiServiceLog.put(LogConstant.LOG_TYPE, LogConstant.LOG_TYPE_SERVICE);

            //请求开始时间
            long startTime = System.currentTimeMillis();

            chain.doFilter(request, resp);

            //请求结束时间
            long endTime = System.currentTimeMillis();
            apiServiceLog.put(LogConstant.EXECUTION_TIME, (double)(endTime - startTime));
            //记录响应日志
            serviceLogSender.sendServiceLog(apiServiceLog);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        //do nothing
    }

    /**
     * 请求参数转json
     * @param req req
     * @return string
     */
    private JSONObject requestParamsToJSON(ServletRequest req) {
        JSONObject jsonObj = new JSONObject();
        Map<String,String[]> params = req.getParameterMap();
        if (params == null || params.isEmpty()) {
            return jsonObj;
        }
        params.forEach((key, value) -> jsonObj.put(key, value.length == 1 ? value[0] : value));
        return jsonObj;
    }

}